package pers.fish.sso.server.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import pers.fish.sso.common.model.Authentication;
import pers.fish.sso.common.util.TicketUtil;
import pers.fish.sso.server.exception.BadCrendentialException;
import pers.fish.sso.server.mapping.TicketDataMappingStorage;
import pers.fish.sso.server.service.ILoginService;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 写点什么吧
 *
 * @author HUAWEI
 * @date 2020/8/18
 */
public abstract class DefaultLoginServiceImpl implements ILoginService {

    @Autowired
    private TicketDataMappingStorage ticketDataMappingStorage;

    @Override
    public String login(String username) {
        Authentication authentication = this.doLogin(username);
        if(authentication == null || authentication.getPrincipal() == null){
            throw new BadCrendentialException("bad crendential exception");
        }
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        String tgt = TicketUtil.generateTgt();
        String ticket = TicketUtil.generateTicket();
        ticketDataMappingStorage.storageAuthentication(ticket,tgt,authentication);
        Cookie cookie = new Cookie(TGT_COOKIE_NAME, tgt);
        response.addCookie(cookie);

        String service = request.getParameter("service");
        if (StringUtils.isEmpty(service)) {
            return "redirect:/success";
        }
        StringBuilder sb = new StringBuilder(service);
        sb.append("?ticket=").append(ticket);

        return "redirect:" + sb.toString();
    }

    protected abstract Authentication doLogin(String username);
}
